package cn.s1995.sloth.bizs.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.s1995.sloth.bizs.constant.CacheNames;
import cn.s1995.sloth.bizs.entity.Demo;
import cn.s1995.sloth.bizs.mapper.DemoMapper;
import cn.s1995.sloth.bizs.service.DemoService;
import cn.s1995.sloth.common.core.util.SpringContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * demo
 *
 * @author Lex
 * @date 2023-12-22 18:27:04
 */
@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> implements DemoService {

    @Override
    @Cacheable(value = CacheNames.demo, key = "#id")
    public Demo getDemo(Long id) {
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transactional(Boolean isException, Boolean isSelf) {
        Demo req = Demo.builder()
                .username("测试")
                .password("测试")
                .age(18)
                .pic("test.jpg")
                .amount(BigDecimal.ZERO)
                .gender(1)
                .build();

        this.save(req);

        if (BooleanUtil.isTrue(isSelf)) {
            this.updateDemo();
        } else {
            SpringContextHolder.getBean(DemoService.class).updateDemo();
        }
    }

    @Override
    // @Transactional(rollbackFor = Exception.class)
    public void updateDemo() {
        update(
                Wrappers.lambdaUpdate(Demo.class)
                        .set(Demo::getUsername, "update")
                        .eq(Demo::getId, 1)
        );
        if (BooleanUtil.isTrue(true)) {
            throw new RuntimeException("测试异常");
        }
    }
}
